﻿using Ardalis.GuardClauses;
using Domain.Users.Events;
using SharedKernel;

namespace Domain.Users;

public  class User : Entity<Guid>, IAggregateRoot
{
    /// <summary>
    /// EF Core 需要的无参构造函数
    /// </summary>
    protected User()
    {
    }

    /// <summary>
    /// 创建新用户
    /// </summary>
    public User(
        string email,
        string firstName,
        string lastName,
        string passwordHash,
        IDateTimeProvider dateTimeProvider)
    {
        Email = Guard.Against.NullOrWhiteSpace(email);
        FirstName = Guard.Against.NullOrWhiteSpace(firstName);
        LastName = Guard.Against.NullOrWhiteSpace(lastName);
        PasswordHash = Guard.Against.NullOrWhiteSpace(passwordHash);
        CreatedAt = Guard.Against.Null(dateTimeProvider).UtcNow;

        // 在聚合根内部触发领域事件
        Raise(new UserRegisteredEvent(Id, Email, FirstName, LastName, CreatedAt));
    }

    public string Email { get; private set; } = string.Empty;
    public string FirstName { get; private set; } = string.Empty;
    public string LastName { get; private set; } = string.Empty;
    public string PasswordHash { get; private set; } = string.Empty;
    public DateTime CreatedAt { get; private set; }

    /// <summary>
    /// 更新用户信息
    /// </summary>
    public void UpdateProfile(string firstName, string lastName)
    {
        FirstName = Guard.Against.NullOrWhiteSpace(firstName);
        LastName = Guard.Against.NullOrWhiteSpace(lastName);
    }

    /// <summary>
    /// 更新邮箱
    /// </summary>
    public void UpdateEmail(string email)
    {
        Email = Guard.Against.NullOrWhiteSpace(email);
    }

    /// <summary>
    /// 更新密码
    /// </summary>
    public void UpdatePassword(string passwordHash)
    {
        PasswordHash = Guard.Against.NullOrWhiteSpace(passwordHash);
    }

    /// <summary>
    /// 获取用户全名
    /// </summary>
    public string GetFullName()
    {
        return $"{FirstName} {LastName}".Trim();
    }
}
